<template>
  <div>
    <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
      <!-- 上拉加载更多 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        offset="50"
        @load="onLoad"
      >
        <ArticleItem
          v-for="item in list"
          :key="item.art_id"
          :theAtrical="item"
          :artID="item.art_id"
          @click.native="artClickFn(item.art_id)"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem.vue'
import { getArticlesAPI } from '@/api/index.js'
export default {
  components: {
    ArticleItem
  },
  data() {
    return {
      list: [],
      loading: true,
      finished: false,
      refreshing: false,
      theTime: new Date().getTime()
    }
  },
  props: {
    ChannelsID: {
      type: Number
    }
  },
  methods: {
    async getArticles() {
      const {
        data: { data }
      } = await getArticlesAPI({
        channel_id: this.ChannelsID,
        timestamp: this.theTime
      })
      this.theTime = data.pre_timestamp
      console.log(data)
      if (this.loading) {
        this.list = [...this.list, ...data.results]
        this.loading = false
      } else if (this.refreshing) {
        this.list = data.results
        this.refreshing = false
      }
      // 当数据加载完毕，结束上拉加载
      if (data.pre_timestamp === null) {
        this.finished = true
      }
    },
    // 底部上拉加载数据
    onLoad() {
      // 异步更新数据
      this.getArticles()
    },
    // 顶部下拉刷新数据
    onRefresh() {
      // 相当于把页码重置为 1
      this.theTime = new Date().getTime()
      // 异步更新数据
      this.getArticles()
    },
    // 点击文章显示详情项
    artClickFn(id) {
      this.$router.push(`/articleDetail?article_id=${id}`)
    }
  },
  created() {
    this.getArticles()
  }
}
</script>

<style></style>
